const router = require('koa-router')()
const { url } = require("../utils/url")
const { verify } = require('../utils/auth');
const response = require('../utils/response');
const fs = require('fs').promises;
const path = require('path');
router.use(verify);
router.post('/upload', async (ctx, next) => {
    const file = ctx.request.files.attach
    ctx.body = {
        code: 200,
        name: file.originalFilename,
        url: url + file.newFilename,
        id: file.newFilename
    }
})
router.post('/delfile', async (ctx, next) => {
    const { ids } = ctx.request.body;
    if (!ids || ids.length === 0) {
        response.error(ctx, { message: '缺少文件ID' });
        return;
    }
    const results = [];
    const errors = [];

    try {
        // 并行处理所有文件的删除操作
        await Promise.all(ids.map(async (id) => {
            const filePath = path.join(__dirname, '../public/attach/', id);
            try {
                // 检查文件是否存在
                await fs.access(filePath);
                // 删除文件
                await fs.unlink(filePath);
                results.push({ id, status: 'deleted' });
            } catch (err) {
                if (err.code === 'ENOENT') {
                    errors.push({ id, error: '文件不存在' });
                } else {
                    errors.push({ id, error: '文件删除失败' });
                }
            }
        }));

        if (errors.length > 0) {
            response.error(ctx, {
                message: '部分文件删除失败',
                data: errors
            });
        } else {
            response.success(ctx, {
                message: '所有文件删除成功',
                data: results
            });
        }
        console.log(errors);
    } catch (err) {
        console.error('Unexpected error:', err);
        response.error(ctx, {
            message: '发生意外错误',
            data: err.message
        });
    }
})
module.exports = router
